##############################################################################
############################## Section 4 Credit contracts 
############################## Shares from all banks, only main banks, all excluding main banks
##############################################################################

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# supress scientific notation
pd.options.display.float_format ='{:.6f}'.format

# paths

path_data = r'P:\ECB business areas\DGR\Staff\papouts\Research\Active\Firm Heterogeneities\Final datasets'
path_output = r'P:\ECB business areas\DGR\Staff\papouts\Research\Active\Firm Heterogeneities\Final charts\Revision'


# use function from file '4_instr_type_shr.py'
def plot_shr(data, color, order):
    # data should be a dataframe
    # color should be a text
    # order should be a list of lists, where the first is order of all countries and the second is selected countries

    # set parameters
    sns.set(rc={'figure.figsize':(15,10), 'axes.labelsize':26, 'axes.titlesize':26,  'axes.labelpad':15, 'xtick.labelsize':26, 'ytick.labelsize':26}, style='white')
    
    # selected countries
    plt.figure()
    data[0].set_index('cntry_dbtr').loc[order[1]].plot(kind='bar', stacked=True, color=colors)
    plt.xlabel('Country', labelpad=6)
    plt.ylabel('Share', labelpad=6)
    plt.xticks(rotation=0)
    p = plt.legend(bbox_to_anchor=(1.20,0), borderaxespad=3.5, ncol=5, prop={'size': 20}, frameon=True, shadow=True)
    plt.savefig(path_output + '\\SectionX_loanshr.pdf', bbox_extra_artists=(p,), bbox_inches='tight', dpi=600)
    

# load data
# csv file with numbers
tbl = pd.read_csv(path_data + r'\Revision\Share_Instr_stata_v2.csv')
tbl.drop(['multirel_share', 'singlerel_share','share_onlymb2', 'share_both2',
       'share_onlyoth2'],axis=1,inplace=True)
   
# order countries by 'both'
tbl1 = tbl.copy()
tbl1.index = tbl1['cntry_dbtr']
tbl1.drop(['cntry_dbtr'],axis=1,inplace=True)
order_sel = tbl1.sort_values(by='share_bothmboth', ascending=False).index

# plot
# rename columns
# reorder columns
tbl = tbl[['cntry_dbtr','share_bothmboth','share_onlymb','share_onlyoth']]
tbl.columns = ['cntry_dbtr','Share from the main and other banks','Share from main bank only','Share from other banks']
colors = ['#d43d4f', '#fdad60', '#3387bc']
plot_shr(data=[tbl], color='Spectral', order=[[], order_sel])  






